﻿using System;
using System.Text;

using Adaptive.Agrona.Concurrent;

using Unity.Type.BinaryType;

namespace Unity.Commons.Client.Statistics
{
    public class UnityStatisticsSerializer
    {
        public const int StatusLength = MessageHeader.Size + Status.BlockLength;
        private static readonly MessageHeader MessageEncoder = new MessageHeader();

        private static readonly Status StatusEncoder = new Status();
        private static readonly byte[] SerializeBuffer = new byte[StatusLength];
        private readonly UnsafeBuffer _buffer = new UnsafeBuffer(SerializeBuffer);

        private static void FillArray<T>(T[] array, T value)
        {
            for(int i = 0; i < array.Length; i++)
            {
                array[i] = value;
            }
        }

        public UnsafeBuffer SerializeStatus(IUnityStatistics statistics, string csiId)
        {
            FillArray(SerializeBuffer, (byte) 0x0);
            StatusEncoder.WrapForEncodeAndApplyHeader(_buffer, 0, MessageEncoder);
            StatusEncoder.ChangerCsiId = int.Parse(csiId);
            StatusEncoder.PublishedStreamIDs = (int)statistics.GetPublishedStream();
            StatusEncoder.PublishedOfflineIds = (int)statistics.GetPublishedOffline();
            StatusEncoder.DroppedIDs = (int)statistics.GetDropped();
            StatusEncoder.TimeDrift = 0;
            StatusEncoder.Fingerprint = null;
            StatusEncoder.GlobalStatus = GlobalStatus.Authenticated; // TODO ? what about new default value
            StatusEncoder.Ident = null;
            StatusEncoder.Version = new ReadOnlySpan<byte>(
                Encoding.ASCII.GetBytes(UnityVersion.GetReleaseVersion().ToString()));
            StatusEncoder.AllGenerated = (int)statistics.GetGenerated();
            StatusEncoder.OnlineBufferCapacity = (int)statistics.GetBufferCapacity();
            StatusEncoder.OnlineBufferSize = (int)statistics.GetBufferSize();
            StatusEncoder.OfflineBufferCapacity = (int)statistics.GetOfflineBufferCapacity();
            StatusEncoder.OfflineBufferSize = (int)statistics.GetOfflineBufferSize();
            return _buffer;
        }

    }
}
